package pers.qianyu.month_202103.date_20210314;

import java.util.*;

/**
 * 705. 设计哈希集合
 * https://leetcode-cn.com/problems/design-hashset/
 *
 * @author mizzle rain
 * @date 2021-03-14 14:05
 */
public class MyHashSet {
    private int cap = 20011;
    private LinkedList[] table = new LinkedList[cap];

    /**
     * Initialize your data structure here.
     */
    public MyHashSet() {
        for (int i = 0; i < cap; i++) {
            table[i] = new LinkedList<Integer>();
        }
    }

    public void add(int key) {
        int h = hash(key);
        for (int i = 0; i < table[h].size(); i++) {
            if (table[h].get(i).equals(key)) {
                return;
            }
        }
        table[h].add(key);
    }

    public void remove(int key) {
        int h = hash(key);
        int i = 0;
        for (; i < table[h].size(); i++) {
            if (table[h].get(i).equals(key)) {
                break;
            }
        }
        if (i != table[h].size()) table[h].remove(i);
    }

    /**
     * Returns true if this set contains the specified element
     */
    public boolean contains(int key) {
        int h = hash(key);
        for (int i = 0; i < table[h].size(); i++) {
            if (table[h].get(i).equals(key)) {
                return true;
            }
        }
        return false;
    }

    private int hash(int key) {
        return key % cap;
    }
}
